package com.sicnu.history.service.aop;


import com.sicnu.history.bean.entity.LogsDO;
import com.sicnu.history.config.HoneyLogs;
import com.sicnu.history.service.impl.LogsServiceImpl;
import com.sicnu.history.util.IpUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;

/**
 * @author 29718
 */
@Aspect
@Component
@Slf4j
public class LogsAspect {

    @Resource
    private LogsServiceImpl logsServiceImpl;

    private final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    @AfterReturning(pointcut = "@annotation(honeyLogs)", returning = "jsonResult")
    public Object recordLogs(JoinPoint joinPoint, HoneyLogs honeyLogs, Object jsonResult) {
        // 获取当前登录用户的用户名
        String username = getCurrentUsername();

        // 获取请求的URL
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String url = request.getRequestURL().toString();

        // 获取请求的IP地址
        String ip = IpUtil.getIpAddr(request);

        // 获取请求的时间
        String time = formatCurrentDateTime();

        // 构建日志记录对象
        LogsDO logsDO = LogsDO.builder()
                .operation(honeyLogs.operation())
                .type(honeyLogs.type().getValue())
                .ip(ip)
                .username(username)
                .time(time)
                .build();

        logsServiceImpl.save(logsDO);

        // 返回原来的结果
        return jsonResult;
    }

    private String formatCurrentDateTime() {
        try {
            // 格式化当前时间
            return LocalDateTime.now().format(formatter);
        } catch (DateTimeParseException e) {
            log.error("Error formatting LocalDateTime: {}", e.getMessage());
            // 返回一个安全的默认时间字符串，或根据需要处理
            return "未知时间";
        }
    }

    private String getCurrentUsername() {
        // 获取当前用户的认证信息
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        // 确保用户已认证
        if (authentication != null && authentication.isAuthenticated()) {
            // 获取用户的 principal
            Object principal = authentication.getPrincipal();
            // 如果 principal 是 UserDetails 的实例
            if (principal instanceof UserDetails) {
                // 获取用户名
                return ((UserDetails) principal).getUsername();
            } else if (principal instanceof String) {
                return (String) principal;
            }
        }
        // 默认返回未知用户
        return "admin";
    }
}
